FROM beiruixing-docker.pkg.coding.net/brx/publicdocker/node:22-alpine AS builder
WORKDIR /app

# 重新定义ARG，使其在FROM之后可用
ARG NODE_ENV

# 设置构建环境变量
ENV NODE_OPTIONS="--max-old-space-size=4096"
ENV PUPPETEER_SKIP_CHROMIUM_DOWNLOAD=true
# 将ARG值设置为ENV，确保在构建脚本中可用
ENV NODE_ENV=${NODE_ENV}

# 输出变量值以便调试
RUN echo "NODE_ENV=${NODE_ENV}"

# 安装系统依赖（增加完整编译套件）
RUN sed -i 's/dl-cdn.alpinelinux.org/mirrors.aliyun.com/g' /etc/apk/repositories \
    && apk update \
    && apk add --no-cache --virtual .build-deps \
    bash \
    curl \
    python3 \
    make \
    g++ \
    git \
    openssl \
    ca-certificates \
    autoconf \
    automake \
    libtool \
    nasm \
    libpng-dev \
    gifsicle \
    vips-dev \
    && rm -rf /var/cache/apk/*

# 配置 Yarn
RUN corepack enable && corepack prepare yarn@1.22.19 --activate \
    && yarn config set registry https://registry.npmmirror.com \
    && yarn config set sass_binary_site https://npmmirror.com/mirrors/node-sass \
    && yarn config set disturl https://npmmirror.com/mirrors/node \
    && yarn config set network-timeout 600000 \
    && yarn config set enable-network-idle false

# 分阶段安装依赖
COPY package.json yarn.lock ./
# 添加重试机制安装依赖
RUN for i in 1 2 3; do \
        echo "Attempt $i: Installing dependencies..." && \
        yarn install \
            --network-timeout 600000 \
            --non-interactive \
            --update-checksums \
            --verbose && break || \
        if [ $i -lt 3 ]; then \
            echo "Retry yarn install in 10 seconds..." && \
            sleep 10; \
        else \
            echo "Failed to install dependencies after 3 attempts" && \
            exit 1; \
        fi \
    done

# 复制项目文件并构建
COPY . .
RUN yarn build:${NODE_ENV}

# 清理构建依赖（生产镜像不需要）
RUN apk del .build-deps

# 生产阶段
FROM beiruixing-docker.pkg.coding.net/brx/publicdocker/nginx:stable-alpine3.17
COPY --from=builder /app/dist /usr/share/nginx/html

COPY nginx.conf  /etc/nginx/conf.d/default.conf.template  

# 启动脚本（下载远程配置并启动 Nginx）
COPY Start.sh  /Start.sh  

# 设置启动脚本权限并定义入口
RUN chmod +x /Start.sh
ENTRYPOINT ["sh","./Start.sh"]
